// pages/player/player.js
let musicList = [];
// 当前播放音乐索引
let nowPlayingId = 0;
// 获取全局唯一的背景音频管理器
const manager = wx.getBackgroundAudioManager();
// 获取全局js
const app = getApp();
let that = this;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    musicInfo: {
      name: "",
      singer: ""
    },
    musicPicUrl: '',
    isPlaying: false,
    progressText: "00:00",
    durationText: "00:00",
    playStatus: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.nowPlayingIndex = options.index;
    // 获取本地歌单
    this.musicList = wx.getStorageSync('musicList');
    this._loadMusicDetail(options.musicId)
    // console.log(this.musicList);
    // 设置导航标题
    wx.setNavigationBarTitle({
      title: this.data.musicInfo.name,
    });

  },
  // 加载歌曲详情
  _loadMusicDetail(musicId) {
    manager.stop()
    wx.showLoading({
      title: '歌曲加载中',
    })
    console.log(musicId);
    // 获取当前歌曲
    const music = this.musicList[this.nowPlayingIndex]
    console.log(music);
    this.setData({
      musicInfo: {
        name: music.name,
      },
      musicPicUrl: music.al.picUrl
    });
    app.setIsPlaying(false)
    this.setData({
      isPlaying: app.getIsPlaying()
    })
    // 设置全局的音乐id
    app.setPlayingMusicId(music.id)
    // 获取歌曲的url
    wx.cloud.callFunction({
      name: 'music',
      data: {
        $url: "musicUrl",
        musicId: musicId
      }
    }).then(res => {
      console.log(res);
      if (res.result.url === null) {
        wx.showToast({
          title: '没有权限',
        })
        return;
      } else {
        manager.src = res.result.url;
        manager.title = music.al.name;

        // manager.currentTime = 0;
        let that = this;
        // manager.onPlay(function () {
        //   console.log("======onPlay======");
        //   that.setData({
        //     playStatus: true
        //   })
        //   that.countTimeDown(that, manager);
        // });
        // manager.onPause(function () {
        //   that.setData({
        //     playStatus: false
        //   })
        //   console.log("======onPause======");
        // });
        manager.onEnded(function () {
          console.log("======onEnded======");
          setTimeout(function () {
            that.onNext();
          }, 1500);
        });

      }
      app.setIsPlaying(true)
      this.setData({
        isPlaying: app.getIsPlaying()
      })
      wx.hideLoading()
    }).catch(err => {
      console.log(err);
    })
  },
  // 点击播放
  playerMusic() {
    app.setIsPlaying(!this.data.isPlaying)
    this.setData({
      isPlaying: app.getIsPlaying()
    });
    // !this.data.isPlaying 
    if (this.data.isPlaying) {
      manager.pause()
    } else {
      manager.play()
    }
    console.log(this.data.isPlaying);

  },
  //切换播放
  onPrev() {
    this.nowPlayingIndex--;
    if (this.nowPlayingIndex < 0) {
      this.nowPlayingIndex = this.musicList.length - 1;
    }
    this._loadMusicDetail(this.musicList[this.nowPlayingIndex].id)
    // 设置导航标题
    wx.setNavigationBarTitle({
      title: this.data.musicInfo.name,
    });
  },
  onNext() {
    this.nowPlayingIndex++;
    if (this.nowPlayingIndex >= this.musicList.length) {
      this.nowPlayingIndex = 0;
    }
    this._loadMusicDetail(this.musicList[this.nowPlayingIndex].id)
    // 设置导航标题
    wx.setNavigationBarTitle({
      title: this.data.musicInfo.name,
    });

  },
  // //循环计时
  // countTimeDown: function (that, manager, cancel) {
  //   if (that.data.playStatus) {
  //     setTimeout(function () {
  //       if (that.data.playStatus) {
  //         that.setData({
  //           progress: Math.ceil(manager.currentTime),
  //           progressText: that.formatTime(Math.ceil(manager.currentTime)),
  //           duration: Math.ceil(manager.duration),
  //           durationText: that.formatTime(Math.ceil(manager.duration))
  //         })
  //         that.countTimeDown(that, manager);
  //       }
  //     }, 1000)
  //   }
  // },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },



  //格式化时长
  // formatTime: function (s) {
  //   let t = '';
  //   s = Math.floor(s);
  //   if (s > -1) {
  //     let min = Math.floor(s / 60) % 60;
  //     let sec = s % 60;
  //     if (min < 10) {
  //       t += "0";
  //     }
  //     t += min + ":";
  //     if (sec < 10) {
  //       t += "0";
  //     }
  //     t += sec;
  //   }
  //   return t;
  // },

})